<?php
$this->headScript()->appendFile('/libs/jquery.weekcalendar.js');
$this->headScript()->appendFile('/libs/date.js');
$this->headScript()->appendFile('/libs/jquery-ui-i18n.js');
$this->headLink()->appendStylesheet('/libs/css/smoothness/jquery-ui-1.8.11.custom.css');
$this->headLink()->appendStylesheet('/libs/css/jquery.weekcalendar.css');
$this->headLink()->appendStylesheet('/libs/calendar_skins/default.css');
$this->headLink()->appendStylesheet('/libs/calendar_skins/gcalendar.css');
$this->headLink()->appendStylesheet('/libs/css/event_types.css');
$this->headLink()->appendStylesheet('/libs/css/event.css');
$namespace= new Zend_Session_Namespace('EventController');
?><br /><br />
  <script type="text/javascript">
  function isInt(number){
      return typeof number==='number' && n%1==0;
  }
  function postToUrl(path, params, method) {
    method = method || "post";
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    for(var key in params) {
	if(params.hasOwnProperty(key)) {
	    var hiddenField = document.createElement("input");
	    hiddenField.setAttribute("type", "hidden");
	    hiddenField.setAttribute("name", key);
	    hiddenField.setAttribute("value", params[key]);
	    form.appendChild(hiddenField);
	 }
    }
    document.body.appendChild(form);
    form.submit();
    }
  (function($) {
    var d = new Date();
    d.setDate(d.getDate() - d.getDay());
    var year = d.getFullYear();
    var month = d.getMonth();
    var day = d.getDate();

    function updateMessage(message) {
      $('#message').fadeOut(function() {
          $('#message').text(message);
        $(this).fadeIn(750);
	setTimeout(function(){
	    $("#message").fadeOut(2500);
	}, 2000);
      });
    }
    function eventsAvailableMessage(message) {
      $('#eventsAvailable').fadeOut(function() {
          $('#eventsAvailable').text(message);
        $(this).fadeIn(750);
	setTimeout(function(){
	    $("#eventsAvailable").fadeOut(2500);
	}, 3000);
      });
    }

    $(document).ready(function() {
    	<?php 
	if(isset($namespace->eventsAvailable) && $namespace->eventsAvailable){
	    ?>
	$('input[name="denied_checkbox"]').attr('checked', true);
	eventsAvailableMessage('Termine für den gelöschten Zeitraum sind vorhanden.');
	<?php
	unset($namespace->eventsAvailable);
	}
	?>
	$('#popup').click(function(){
	   $('#popup').slideUp();
	   $('#popup #loading').show();
	   $('#popup #child_data').hide();
	});
	$('#calendar_selection').hover(function(){
	    $('#calendar_category_selection').slideDown(750);
	},function(){
	    setTimeout(function(){
	    $('#calendar_category_selection').slideUp(750);
	}, 2000);
	});
	$('input[name="category_checkbox"],input[name="denied_checkbox"]').change(function(){
	    $calendar.weekCalendar('refresh');
	    updateMessage('Termine wurden geladen.');
	});
      var $calendar = $('#calendar').weekCalendar({
	timeslotsPerHour: 4,
        timeslotHeight: 20,
	scrollToHourMillis : 500,
	use24Hour: true,
	hourLine: true,
	users: 1,
        defaultFreeBusy: {free: true},
	allowCalEventOverlap: true,
	overlapEventsSeparate: true,
        height: function($calendar){
          return $(window).height() - $('h1').outerHeight(true);
        },
	<?php 
	if(isset($namespace->startDate)){
	    ?>
	date : new Date('<?=$namespace->startDate?>'),		    
	    <?php
	}
	?>
	eventClick : function(calEvent, element, freeBusyManager, $calendar, DomEvent){
	    if(calEvent.category=='Fester Termin' ||
	       calEvent.category=='Einzeltermin' ||
	       calEvent.category=='Eingewöhnungstermin'){
		 $('#popup').slideDown();
		 $.getJSON("event/childeventdetail", {
		    eventID: calEvent.id
		 }, function(result) {
			if(result.status!=0){
			     $('#popup').slideUp(750);
			     updateMessage('<b>Fehler '+result.status+'</b><br />'+result.message);
			}
			updateMessage(result.message);
			$('#confirm a').attr('href','/event/delete?id='+result.event.id);
			$('#buttonright').attr('href', window.location.href+'/update/id/'+calEvent.id);
			$('#popup ul li:nth-child(2)').text(result.child.forename);
			$('#popup ul li:nth-child(4)').text(result.child.surname);
			$('#popup ul li:nth-child(6)').text(result.child.comment);
			$('#popup ul li:nth-child(8)').text(result.event.description);
			$('#popup ul li:nth-child(10)').text(result.child.ranking_points);
			$('#popup ul li:nth-child(12)').text(result.event.event_type);
			if(result.parent1 instanceof Object){
			    $('#popup ul li:gt(11)').show();
			    $('#popup ul li:nth-child(16)').text(result.parent1.forename);
			    $('#popup ul li:nth-child(18)').text(result.parent1.surname);
			    $('#popup ul li:nth-child(20)').text(result.parent1.telnumber);
			}else
			    $('#popup ul li:gt(11)').hide();
			if(result.parent2 instanceof Object){
			    $('#popup ul li:gt(19)').show();
			    $('#popup ul li:nth-child(24)').text(result.parent2.forename);
			    $('#popup ul li:nth-child(26)').text(result.parent2.surname);
			    $('#popup ul li:nth-child(28)').text(result.parent2.telnumber);
			}else
			    $('#popup ul li:gt(19)').hide();
			$('#popup #loading').hide();
			$('#popup #child_data').show();
		 });
	     }else{
                  if(calEvent.category!='Arbeitszeiten')
                      window.location.href=window.location.href+'/update/id/'+calEvent.id;
	     }
	},
	draggable   : function(calEvent, $event) {
	    if (calEvent.category=='Abgesagter Termin' ||
		calEvent.category=='Arbeitszeiten'){
		return false;
	    }else
		return true;
	},
	resizable   : function(calEvent, $event) {
	    if (calEvent.category=='Abgesagter Termin' ||
		calEvent.category=='Arbeitszeiten'){
		return false;
	    }else
		return true;
	},
        eventRender : function(calEvent, $event) {
	  if (calEvent.category=='Fester Termin'){
	      $event.addClass("calEvent_fixed");
	  }
	  if (calEvent.category=='Einzeltermin'){
	      $event.addClass("calEvent_single");
	  }
	  if (calEvent.category=='Abgesagter Termin' || calEvent.status=='Abgelehnt'){
	      $event.addClass("calEvent_canceled");
	      $event.find('.wc-title').before('<img class="symbol floatleft" src="/img/cancel.png" alt="Dieser Termin ist abgesagt" />');
	  }
	  if (calEvent.category=='Eingewöhnungstermin'){
	      $event.addClass("calEvent_adeption");
	  }
	  if (calEvent.category=='Gesprächstermin'){
	      $event.addClass("calEvent_talk");
	  }
	  if (calEvent.category=='Konferenz'){
	      $event.addClass("calEvent_meeting");
	  }
	  if (calEvent.category=='Fest/Veranstaltung'){
	      $event.addClass("calEvent_celebration");
	  }
	  if (calEvent.category=='sonstiges'){
	      $event.addClass("calEvent_other");
	  }
          if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css('backgroundColor', '#aaa');
            $event.find('.wc-time').css({
              backgroundColor: '#999',
              border:'1px solid #888'
            });
          }
	  if (calEvent.series!=null){
	      $event.addClass("calEvent_series");
	      $event.find('.wc-title').before('<img class="symbol floatright" src="/img/button_black_repeat.png" alt="Dieser Termin ist Teil einer Terminserie" />');
	  }
        },
	eventDrop : function(calEvent,element){
	    postToUrl('/event/update/id/'+calEvent.id.toString(),{date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),date_to:calEvent.end.toString('dd.MM.yyyy HH:mm')});
	},
	eventResize : function(newCalEvent,oldCalEvent,element){
	    postToUrl('/event/update/id/'+oldCalEvent.id.toString(),{date_to:newCalEvent.end.toString('dd.MM.yyyy HH:mm')});
	},
        eventNew : function(calEvent, $event, FreeBusyManager, calendar) {
          var isFree = true;
          $.each(FreeBusyManager.getFreeBusys(calEvent.start, calEvent.end), function() {
            if (
              this.getStart().getTime() != calEvent.end.getTime()
              && this.getEnd().getTime() != calEvent.start.getTime()
              && !this.getOption('free')
            ){
              isFree = false;
              return false;
            }
          });

          if (!isFree) {
            alert('looks like you tried to add an event on busy part !');
            $(calendar).weekCalendar('removeEvent',calEvent.id);
            return false;
          }
	  //alert(calEvent.start.toISOString());
	  postToUrl('/event/create',{date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),date_to:calEvent.start.addHours(1).toString('dd.MM.yyyy HH:mm')});
          calEvent.id = calEvent.userId +'_'+ calEvent.start.getTime();
          $(calendar).weekCalendar('updateFreeBusy', {
            userId: calEvent.userId,
            start: calEvent.start,
            end: calEvent.end,
            free:false
          });
        },
        data: function(start, end, callback) {
          var dataSource = $('#data_source').val();
	    var selectedCategories  = new Array();
	    $("input[name='category_checkbox']:checked").each(function() {
		selectedCategories.push($(this).val());
	    });
	    $.getJSON("event/", {
		startDate: start.toISOString(),
		endDate: end.toISOString(),
		categories: selectedCategories,
		denied: $("input[name='denied_checkbox']:checked").val()
	    },  function(result) {
		callback(result);
		updateMessage('Termine wurden geladen.');
	    });
        },
        showAsSeparateUser: false, 
        displayOddEven: true,
        displayFreeBusys: true,
        daysToShow: 5,
        switchDisplay: {'ein Tag': 1, '3 Tage': 3, 'Arbeitswoche': 5, 'Woche': 7},
        headerSeparator: ' ',
        useShortDayNames: true,
        // I18N
        firstDayOfWeek: $.datepicker.regional['de'].firstDay,
        shortDays: $.datepicker.regional['de'].dayNamesShort,
        longDays: $.datepicker.regional['de'].dayNames,
        shortMonths: $.datepicker.regional['de'].monthNamesShort,
        longMonths: $.datepicker.regional['de'].monthNames,
        dateFormat: 'd. F y'
      });
    });
  })(jQuery);
  </script>
<div id="event_index">
  <div id="message" class="ui-corner-all"></div>
    <div id="eventsAvailable" class="ui-corner-all hidden"></div>
  <div id="calendar_selection" class="ui-corner-all">
    <div id="category_toggle" class="ui-corner-all">
      <strong><a href="#">Kategorien auswählen...</a></strong>
    </div>
    <div id="calendar_category_selection" class="ui-corner-all hidden">
      <ul>
	  <li><input type="checkbox" name="category_checkbox" value="Fester Termin" checked />Fester Termin</li>
	  <li><input type="checkbox" name="category_checkbox" value="Einzeltermin" checked />Einzeltermin</li>
	  <li><input type="checkbox" name="category_checkbox" value="Eingewöhnungstermin" checked />Eingewöhnungstermin</li>
	  <li><input type="checkbox" name="category_checkbox" value="Gesprächstermin" checked />Gesprächstermin</li>
	  <li><input type="checkbox" name="category_checkbox" value="Konferenz" checked />Konferenz</li>
	  <li><input type="checkbox" name="category_checkbox" value="Fest/Veranstaltung" checked />Feste/Veranstaltungen</li>      
	  <li><input type="checkbox" name="category_checkbox" value="Sonstiges" checked/>Sonstiges</li>
	  <li><input type="checkbox" name="category_checkbox" value="Arbeitszeiten" />Arbeitszeiten</li>
	  <li><input type="checkbox" name="category_checkbox" value="Abgesagter Termin" />Abgesagter Termin</li>
	  <li><input type="checkbox" name="denied_checkbox" value="both" />Abgelehnte</li>
      </ul>
    </div>  
  </div>

  <div id="calendar"></div> 
  
 <!--    <strong> <a href="#" class="show">div aufklappen</a></strong> -->
     <div id="popup" class="hidden ui-corner-all">
	 <div id="loading">
	     <img src="img/loading.gif" />
	 </div>
	 <div id="child_data" class="hidden">
	    <h3>Kind</h3>
	    <ul>
		<li>Vorname:</li><li>Kevin</li>
		<li>Nachname:</li><li>Gruselmich</li>
		<li>Kommentar</li><li>etwas ängstlich und schreckhaft, oft maskiert</li>
		<li>Termininfo</li><li>Heute demaskierend auf Kevin einwirken</li>
		<li>Ranking-Punkte:</li><li>150K</li>
		<li>Termintyp:</li><li>Fester Termin</li>
		<li>Elternteil 1:</li><li>&nbsp;</li>
		<li>Vorname:</li><li>Jaqueline</li>
		<li>Nachname:</li><li>Gruselmich</li>
		<li>Telefon</li><li>0900 110110</li>
		<li>Elternteil 2:</li><li>&nbsp;</li>
		<li>Vorname:</li><li>Horst-Heinrich</li>
		<li>Nachname:</li><li>Gruselmich</li>
		<li>Telefon</li><li>0900 110110</li>
	    </ul>
	    <form><?php /*
		<input class="floatleft" type="button" name="cancel" value="Termin absagen" onclick="$('#confirm').slideDown();" />*/?><a id="buttonright" class="floatright" href="/event/update">Bearbeiten!</a>
	    </form>
	 </div>
     </div>
<?php /*<div id="confirm" class="hidden ui-corner-all">
	     <h3>Termin absagen?</h3>
	     <p>Möchten sie diesen Termin wirklich absagen?<br />
	     Nicht-Betreungstermine werden dann endgültig gelöscht!</p>
	     <input class="floatleft" type="button" name="cancel" value="Nein/Abbrechen" onclick="$('#confirm').slideUp();" /><a class="floatright" href="/event/delete/">Ja!</a>
	 </div>
</div>*/?>
